package com.pucrs.br.loggen;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SyslogAppender;

public class App {

	private static final Logger syslog = Logger.getLogger(App.class);

	private static int syslogFacility = SyslogAppender.LOG_USER;

	private static Random rd = new Random();

	public static void main(String[] args) throws Exception {
		if (args.length == 2) {
			System.out.println("########## LOGGEN ###########");
			System.out.println("APP-NAME [" + args[0] + "]");
			System.out.println("SYSLOG_HOST [" + args[1] + "]");
			System.out.print("Running");
			App main = new App(args[0], args[1]);
			main.execute();
		} else {
			throw new Exception("use 'java -jar logGen.jar <app-name> <syslog_host>'");
		}
	}

	public App(String appName, String host) {
		PatternLayout pattern = new PatternLayout("%d{MMM dd HH:mm:ss} " + appName + ": %-5p %m%n");
		syslog.addAppender(new SyslogAppender(pattern, host, syslogFacility));
		syslog.setLevel(Level.ALL);
	}

	private void execute() {
		try {
			while (true) {
				if (rd.nextBoolean()) {
					syslog.error(getRandomMessage());
				}
				if (rd.nextBoolean()) {
					syslog.debug(getRandomMessage());
				}
				if (rd.nextBoolean()) {
					syslog.fatal(getRandomMessage());
				}
				if (rd.nextBoolean()) {
					syslog.info(getRandomMessage());
				}
				if (rd.nextBoolean()) {
					syslog.trace(getRandomMessage());
				}
				if (rd.nextBoolean()) {
					syslog.warn(getRandomMessage());
				}
				Thread.sleep(10);
				System.out.print(".");
			}
		} catch (Exception e) {
			System.err.println(e);
			System.exit(-1);
		}
	}

	private String getRandomMessage() throws IOException {
		int line = rd.nextInt(455);
		int i = 0;
		String message = "";
		BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("messages.txt")));
		while (i != line) {
			message = reader.readLine();
			i++;
		}
		return message;
	}

}
